import React from 'react'
import NavBar from '../component/NavBar'
import asymeth from '../store/asyncMethod/asyncmethod'
import Loading from './Loading'
import {
  connect, //  用于连接数据映射和修改数据映射方法的连接函数 返回值是一个新的组件
} from 'react-redux'
import '../assets/css/Special.css'

class Myapp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      typeList: [],
    }
  }
  componentDidMount() {
    this.getType()
  }
  render() {
    // console.log(this.props)
    if (this.state.typeList.length === 0) {
      return (
        <div>
          <NavBar params={this.props} name="专项答题"></NavBar>
          <Loading></Loading>
        </div>
      )
    } else {
      let typeList = this.state.typeList
      return (
        <div className="Special_bg">
          <NavBar params={this.props} name="专项答题"></NavBar>
          <div>
            <p className="title_special">专题细分练习</p>
            <div className="ItemForm">
              <div className="Item">
                {typeList.map((item, index) => {
                  return (
                    <div
                      key={index}
                      className={index % 2 === 1 ? 'left_part' : 'right_part'}
                      onClick={() => {
                        this.selectType(item.type)
                      }}
                    >
                      <div>{index + 1}</div>
                      <div>{item.type}</div>
                      <div>{item['COUNT(*)']}题</div>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </div>
      )
    }
  }
  getType = async () => {
    let res = await asymeth.getType()
    if (res.data.code === 200) {
      this.setState({
        typeList: res.data.result,
      })
      // console.log('mmmm', this.state.typeList)
    }
  }

  selectType = async type => {
    let params = {}
    params.type = type
    await this.props.setTypeQuestionList(params)
    // console.log(this.props)
    this.props.history.push('/singer', { type: 'Special', name: type })
    // console.log(this.props)
  }
}

// 将state银映射到props中
function mapStateToProps(state) {
  return {
    typeQuestionList: state.typeQuestionList,
  }
}

// 进啊给修改state数据的方法映射到props
function mapDispatchToProps(dispatch) {
  return {
    setTypeQuestionList: async params => {
      let res = await asymeth.setTypeQuestionList(params)
      if (res.data.code === 200) {
        dispatch({ type: 'setTypeQuestionList', content: res.data.result })
        return
      }
      dispatch({ type: 'setTypeQuestionList', content: '题目获取失败' })
    },
  }
}

const Special = connect(mapStateToProps, mapDispatchToProps)(Myapp)

export default Special
